package com.longy.springcloud.controller;

import cn.hutool.core.util.IdUtil;
import com.longy.springcloud.domain.CommonResult;
import com.longy.springcloud.domain.Payment;
import com.longy.springcloud.service.PaymentService;
import com.longy.springcloud.service.testService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class PaymentController {
    @Resource
    private PaymentService paymentService;

    @Resource
    private DiscoveryClient discoveryClient;

    @Resource
    private testService testService;

    @Value("${server.port}")
    private String serverPort;

    @GetMapping(value = "/testFeign")
    public String testFeign() {
//        //模拟线程处理时间较长
//        try {
//            TimeUnit.SECONDS.sleep(3);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        return "这是8001的testFeign";
    }
    @PostMapping(value = "Payment/Creat")
    public CommonResult Creat(@RequestBody Payment payment) {
        int result = paymentService.Creat(payment);
        log.info("插入结果" + result);
        if (result > 0) {
            return new CommonResult(200, "插入成功,serverPort："+serverPort);
        } else {
            return new CommonResult(201, "插入失败");
        }
    }

    @GetMapping(value = "Payment/getPaymentById/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id) {
        Payment paymentById = paymentService.getPaymentById(id);
        log.info("查询结果" + paymentById);
        System.out.println("8001--------------------------------------------");
        return new CommonResult(200, "查询成功，serverPort:"+serverPort, paymentById);
    }


    @GetMapping(value = "Payment/lb")
    public String getPaymentLb() {
        return serverPort;
    }


    @GetMapping(value = "/payment/discovery")
    public Object discovery(){
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("service:"+service);
        }

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info(instance.getInstanceId()+"\t"+instance.getHost()+"\t"+instance.getPort()+"\t"+instance.getUri());
        }
        return this.discoveryClient;
    }

    @GetMapping(value = "/payment/feign/timeout")
    public String timeout(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }
    @GetMapping(value = "/payment/feign/TransactionalTest/{id}")
    public String TransactionalTest(@PathVariable("id") Long id){
        String sout = testService.sout();


        return sout;
    }

    //=====服务熔断
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),// 是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),// 请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"), // 时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),// 失败率达到多少后跳闸
    })
    @GetMapping(value = "/payment/paymentCircuitBreaker/{id}")
    public String paymentCircuitBreaker(@PathVariable("id") Integer id) {
        if(id < 0)
        {
            throw new RuntimeException("******id 不能负数");
        }
        //生成随机UUID，返回
        String serialNumber = IdUtil.simpleUUID();

        return Thread.currentThread().getName()+"\t"+"调用成功，流水号: " + serialNumber;
    }
    @GetMapping("/payment/zipkin")
    public String paymentZipkin() {
        return "hi ,i'am paymentzipkin server fall back，welcome to atguigu，O(∩_∩)O哈哈~";
    }

}
